﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MiniFox.Components;
using MiniFox.Infrastructure;
using MiniFox.Platform;
using MiniFox.Utility;
using MiniFox.Web;
using MiniFox.Web.Infrastructure;

namespace Wechat.Core
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class WechatControllerBase<T> : MvcControllerBase where T : IWechatService
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected virtual T CreateService(string name)
        {
            return ComponentFactory.GetComponent<T>(name);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name">公众号配置名称</param>
        /// <param name="adapter">网关适配名称</param>
        /// <param name="service">服务名称</param>
        /// <param name="request">请求内容</param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> GatewayAsync([FromRoute(Name = GlobalKey.NAME)] string name, string adapter, string service, HttpRequestMessage request)
        {
            var requestData = await request.Content.ReadAsStringAsync();
            var wechatService = this.CreateService(name);
            string responseData = await wechatService.InvokeAPIAsync(adapter, service, request.Method.Method, request.RequestUri.GetQueryString(), request.Headers.ToNameValueCollection(), requestData);
            HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            response.Content = new StringContent(responseData);
            return response;
        }

        #region 刷新 access token
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public virtual Response RefreshAccessToken([FromRoute(Name = GlobalKey.NAME)] string name)
        {
            var service = this.CreateService(name);
            service.ResetAccessToken();
            Response response = new Response();
            return response;
        }
        #endregion
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        public abstract HttpResponseMessage Validate(string name, string signature, string timestamp, string nonce, string echostr);
    }
}
